package custom.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import common.Constant;
import common.util.SystemProperties;

@Controller
public class MediaController extends BaseController {

	@RequestMapping(value = "/image")
	public ModelAndView download(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("fileName") String fileName,
			@RequestParam("type") String resolutionType) throws Exception {
		String extention = SystemProperties.getProperty(Constant.PROPERTIES_NAME.FILE_EXTENTION.THUMBNAIL);
		StringBuffer url = new StringBuffer();
		url.append(SystemProperties.getProperty(Constant.PROPERTIES_NAME.DIRECTORY.IMAGE_PRE));
		if ("thumbnail".equals(resolutionType)){
			url.append(SystemProperties.getProperty(Constant.PROPERTIES_NAME.DIRECTORY.SUB_URL.IMAGE.THUMB));
		} else if ("org".equals(resolutionType)){
			url.append(SystemProperties.getProperty(Constant.PROPERTIES_NAME.DIRECTORY.SUB_URL.IMAGE.ORIGINAL));
		}
		url.append(fileName).append(".").append(extention);
				
		File file = new File(url.toString());
		
		FileInputStream fis = new FileInputStream(file);
		
		if (fis != null) {
			try {
				response.setContentType("image/"+extention);
				FileCopyUtils.copy(fis, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				fis.close();
			}
		}
		
		return null;
	}

	@RequestMapping(value = "/video")
	public ModelAndView video(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("fileName") String fileName)
			throws Exception {
		StringBuffer url = new StringBuffer();
		url.append(SystemProperties.getProperty(Constant.PROPERTIES_NAME.DIRECTORY.VIDEO_PRE))
			.append(SystemProperties.getProperty(Constant.PROPERTIES_NAME.DIRECTORY.SUB_URL.VIDEO.ORIGINAL))
			.append(fileName);
				
		File file = new File(url.toString());

		FileInputStream fis = new FileInputStream(file);

		if (fis != null) {
			try {
				response.setContentType("video/x-msvideo");
				FileCopyUtils.copy(fis, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				fis.close();
			}
		}

		return null;

	}
}
